package com.fita.admin.web.controller.view;

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @author: 11200
 * @date: 2019/7/3
 */
public class Excel2TemplateView extends ExcelTemplateView {

    private static final Logger logger = LoggerFactory.getLogger(Excel2TemplateView.class);

    /**
     * @param templateXLSFile
     */
    public Excel2TemplateView(String templateXLSFile) {
        super(templateXLSFile);
    }

    /**
     * @param templateXLSFile
     * @param fileName
     */
    public Excel2TemplateView(String templateXLSFile, String fileName) {
        super(templateXLSFile, fileName);

    }

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("Start exporting excel file: " + this.templateXLSFile);
        File template = ResourceUtils.getFile("classpath:template/" + this.templateXLSFile);
        response.setHeader("Content-Disposition", getContentDisposition());
        // no cache here
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        response.setContentType(super.getContentType());
        logger.info("Running Object Collection demo");
        Context context = new Context();
        Set<Map.Entry<String, Object>> entries = model.entrySet();
        entries.stream().forEach(i -> context.putVar(i.getKey(), i.getValue()));
        JxlsHelper.getInstance().processTemplate(new FileInputStream(template), response.getOutputStream(), context);
        logger.info("End exporting excel file: " + this.templateXLSFile);
    }
}
